package com.example.chinawenddingexpo.service;

import com.example.chinawenddingexpo.model.Event;
import com.example.chinawenddingexpo.repository.EventRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class EventService {
    
    @Autowired
    private EventRepository eventRepository;
    
    public List<Event> getAllAvailableEvents() {
        return eventRepository.findAvailableEvents(LocalDateTime.now());
    }
    
    public List<Event> getEventsByType(Event.EventType type) {
        return eventRepository.findByEventTypeAndStatusOrderByStartTimeAsc(type, Event.EventStatus.AVAILABLE);
    }
    
    public List<Event> getUpcomingEvents() {
        return eventRepository.findByStartTimeAfterOrderByStartTimeAsc(LocalDateTime.now());
    }
    
    public List<Event> getEventsByExhibitor(Long exhibitorId) {
        // 暂时返回空列表，因为Event实体中没有exhibitor关联
        return List.of();
    }
    
    public Event getEventById(Long id) {
        Optional<Event> event = eventRepository.findById(id);
        return event.orElse(null);
    }
    
    public Event saveEvent(Event event) {
        return eventRepository.save(event);
    }
    
    public boolean isEventAvailable(Long eventId) {
        Event event = getEventById(eventId);
        return event != null && 
               event.getStatus() == Event.EventStatus.AVAILABLE && 
               event.getCurrentParticipants() < event.getMaxParticipants() &&
               event.getStartTime().isAfter(LocalDateTime.now());
    }
    
    public void incrementParticipants(Long eventId) {
        Event event = getEventById(eventId);
        if (event != null) {
            event.setCurrentParticipants(event.getCurrentParticipants() + 1);
            if (event.getCurrentParticipants() >= event.getMaxParticipants()) {
                event.setStatus(Event.EventStatus.FULL);
            }
            eventRepository.save(event);
        }
    }
}